var express = require('express');
var router = express.Router();

const moment = require('moment')
const AccountModel = require('../../models/AccountModel')

const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

router.get('/', function (req, res, next) {
  res.redirect('/account')
})
/* GET home page. */
router.get('/account', checkLoginMiddleware, async (req, res) => {
  const page = parseInt(req.query.page) || 1; // Get current page, default to 1
  let limit = parseInt(req.query.limit) || 1; // Get items per page from query, default to 10
  const skip = (page - 1) * limit;

  try {
    const accounts = await AccountModel.find().skip(skip).limit(limit);
    const totalAccounts = await AccountModel.countDocuments();
    const totalPages = Math.ceil(totalAccounts / limit);

    res.render('list', { accounts, currentPage: page, totalPages, totalAccounts, moment ,limit});
  } catch (error) {
    console.error(error);
    res.status(500).send('Server Error');
  }
});


router.get('/account/create', checkLoginMiddleware, function (req, res, next) {
  res.render('create', { title: 'Express' });

});

// 添加账单
router.post('/account', checkLoginMiddleware, function (req, res, next) {
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }, (err, data) => {
    if (err) {
      res.status(500).send('插入失败~~');
      return
    }
    res.render('success', {
      msg: '添加成功',
      url: '/account'
    })
  })
});

router.get('/account/:id', checkLoginMiddleware, function (req, res, next) {
  AccountModel.deleteOne({ _id: req.params.id }, (err, data) => {
    if (err) {
      res.status(500).send('删除失败~~')
      return
    }
    res.render('success', {
      msg: '删除成功',
      url: '/account'
    });
  })
});

module.exports = router;
